package leetcode.hot100;

import leetcode.tester.ArgsEnum;
import leetcode.tester.Tester;

import java.util.HashMap;
import java.util.Map;

/**
 * 1. 两数之和
 * https://leetcode.cn/problems/two-sum/?envType=study-plan-v2&envId=top-100-liked
 *
 * @author Liu Yicong
 * @date 2025/9/28
 */
public class Hot1HashTwoSum {
	// 示例 main 函数
	public static void main(String[] args) {
		// 例如测试 TwoSum 类的 twoSum 方法
		Object[][] inputs = {
				new Object[]{new int[]{2, 7, 11, 15}, 9},
				new Object[]{new int[]{3, 2, 4}, 6},
				new Object[]{new int[]{3, 3}, 6}
		};
		Object[] outputs = {
				new int[]{0, 1},
				new int[]{1, 2},
				new int[]{0, 1}
		};

		Tester.test(Tester.wrap(new Hot1HashTwoSum()::twoSum), inputs, outputs, new ArgsEnum[]{ArgsEnum.IGNORE_ORDER});
		Tester.test(Tester.wrap(new Hot1HashTwoSum()::twoSumOpt), inputs, outputs, new ArgsEnum[]{ArgsEnum.IGNORE_ORDER});
	}

	public int[] twoSum(int[] nums, int target) {
		for (int i = 0; i < nums.length; i++) {
			for (int j = i + 1; j < nums.length; j++) {
				if (nums[i] + nums[j] == target) {
					return new int[]{i, j};
				}
			}
		}
		return null;
	}

	private int[] twoSumOpt(int[] nums, int target) {
		Map<Integer, Integer> map = new HashMap<>();
		for (int i = 0; i < nums.length; i++) {
			Integer idx = map.getOrDefault(target - nums[i], -1);
			if (idx == -1) {
				map.put(nums[i], i);
			} else {
				return new int[]{i, idx};
			}
		}
		return null;
	}

}
